package httpproxymiddleware

import (
	"errors"
	"fmt"
	"go-gateway-learn/dao"
	"go-gateway-learn/middleware"
	"go-gateway-learn/public"
	"strings"

	"github.com/gin-gonic/gin"
)

func HTTPWhiteIPListMiddleware() gin.HandlerFunc{
	return func (c *gin.Context)  {
		serverInterface, ok := c.Get("service")
		if !ok{
			middleware.ResponseError(c, 2001, errors.New("service not found"))
			c.Abort()
			return
		}
		serviceDetail := serverInterface.(*dao.ServiceDetail)
		ipList := []string{}
		if serviceDetail.AccessControl.WhiteList != ""{
			ipList = strings.Split(serviceDetail.AccessControl.WhiteList, ",")
		}
		if serviceDetail.AccessControl.OpenAuth == 1 && len(ipList) >0{
			if !public.InStringSlice(ipList, c.ClientIP()){
				middleware.ResponseError(c, 3001, fmt.Errorf("%s not in white ip list" , c.ClientIP()))
				c.Abort()
				return
			}
		}
		c.Next()
	}
}